<?php

/**
 * 仓库
 * @author wangwx 2015-5-7
 */
namespace common\repositories\myhtsq;

use common\entities\myhtsq\ApplicationInfoEntity;
use common\repositories\BaseRepository;
use common\entities\myhtsq\ContractApplicationEntity;
use common\repositories\common\MyscrmContractSyncDeleteDataRepository;
use common\support\StringHelper;
use common\services\common\MyscrmContractApplicationService;
use common\services\myhtsq\ContractService;

class ContractApplicationRepository extends BaseRepository
{


    public static $strToSignTypeMap=['新签'=>1,'续签'=>3,'增购'=>2];
    /**
     * 构造方法
     * @param unknown $config (optional)
     */
    public function __construct($config = [])
    {
        parent::__construct($config);
    }

    /**
     * 处理合同签约产品数组
     * @param int $contractId 合同id
     * @modify zhoud01 contract_id + application_id + rent_period 必须确定唯一一条
     * @param array $productArr 签约合同数组
     * @return boolean
     */
    public static function handleApplicationData($contractId, $productArr)
    {

        if (empty($productArr)) {//没有产品，直接返回
            return true;
        }

        foreach ($productArr as $key => $val) {
            //处理其他产品的情况
            if($val["application_id"]=="other"){
                $val["application_id"]=$val["other_application_id"];
            }
            if (!isset($val['__type'])) {
                $val['__type'] = 'update';
            }
            if(isset($val['really_price']) && $val['really_price']){
                $val['real_deal_amount'] = $val['really_price'];
            }else{
                if(!isset($val['real_deal_amount'])){
                    $val['real_deal_amount'] = 0;
                }
            }
            switch ($val['__type']) {
                case 'add':
                    $myscrmContractApplicationEntity = new ContractApplicationEntity();

                    $applicationInfoAtContractDB = MyscrmContractApplicationService::getApplicationInfoByApplicationId($val['application_id']);
                    $applicationPriceInfo = ApplicationPriceRepository::getApplicationPriceByApplicationId($val['application_id']);

                    $matching_rule = (int)$applicationInfoAtContractDB['matching_rule'];
                    $applicationPrice = isset($applicationPriceInfo['price']) ? $applicationPriceInfo['price'] : 0;

                    $where = [];
                    $where = self::getmatchingRule($matching_rule,$contractId,$val);

                    $myscrmContractApplicationInfo = $myscrmContractApplicationEntity::find()->where($where)->asArray()->one();

                    if(empty($myscrmContractApplicationInfo)){//exl 中约定的进行约束
                        $myscrmContractApplicationEntity->load($val, '');
                        //set benchmark_amount equal amount
                        $myscrmContractApplicationEntity->benchmark_amount = $myscrmContractApplicationEntity->benchmark_amount > 0 ? $myscrmContractApplicationEntity->benchmark_amount : $myscrmContractApplicationEntity->amount;
                        $myscrmContractApplicationEntity->contract_application_id = StringHelper::uuid();
                        $myscrmContractApplicationEntity->contract_id = $contractId;
                        $myscrmContractApplicationEntity->price = $applicationPrice;

                        if ($val['is_standard'] == '0') {
                            $myscrmContractApplicationEntity->is_standard = 0;
                        }

                        $myscrmContractApplicationEntity->save();

                    }elseif ($matching_rule == null){
                        $myscrmContractApplicationEntity->load($val, '');
                        //set benchmark_amount equal amount
                        $myscrmContractApplicationEntity->benchmark_amount = $myscrmContractApplicationEntity->benchmark_amount > 0 ? $myscrmContractApplicationEntity->benchmark_amount : $myscrmContractApplicationEntity->amount;
                        $myscrmContractApplicationEntity->contract_application_id = StringHelper::uuid();
                        $myscrmContractApplicationEntity->contract_id = $contractId;
                        if ($val['is_standard'] == '0') {
                            $myscrmContractApplicationEntity->is_standard = 0;
                        }
                        $myscrmContractApplicationEntity->save();

                    }

                    break;
                case 'delete':
                    if (!empty($val['contract_application_id'])) {
                        //同步要删除的数据到商机系统
                        /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
                        $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());
                        $deleteData = ContractApplicationEntity::findAll([
                            'contract_id' => $contractId,
                            'contract_application_id' => $val['contract_application_id']
                        ]);

                        $deleteResult = ContractApplicationEntity::deleteAll([
                            'contract_id' => $contractId,
                            'contract_application_id' => $val['contract_application_id']
                        ]);

                        if($deleteResult > 0) {
                            foreach ($deleteData as $data) {
                                $contractSyncDeleteDataRepository->add(ContractApplicationEntity::tableName(), 'contract_application_id', $data['contract_application_id']);
                            }
                        }
                    }
                    break;
                case 'update':
                case '':

                    $myscrmContractApplicationEntity = new ContractApplicationEntity();
                    $applicationInfoAtContractDB = MyscrmContractApplicationService::getApplicationInfoByApplicationId($val['application_id']);
                    $matching_rule = (int)$applicationInfoAtContractDB['matching_rule'];

                    $where = [];
                    $where = self::getmatchingRule($matching_rule,$contractId,$val);



                    //接口处可修改 若有争议待商榷
//                    $myscrmContractApplicationInfo = $myscrmContractApplicationEntity::find()->where($where)->asArray()->one();
//                    if(!empty($myscrmContractApplicationInfo)){//只能修改成目前不存在的
//                        unset($val['contract_type']);
//                        unset($val['rent_period']);
//                    }
                    
                    $ContractService = new ContractService();

                    $status = '未开始';

                    $applications = $ContractService->getContractInfo($contractId)['application'];

                    foreach ($applications as $application){
                        if($application['contract_application_id'] == $val['contract_application_id']){
                            $status = $application['status'];
                            break;
                        }
                    }

                    if($status === '未开始'){
                        $myscrmContractApplicationInfo = $myscrmContractApplicationEntity::find()->where(['contract_application_id' => $val['contract_application_id']])->one();
                        $myscrmContractApplicationInfo->load($val, '');
                        $myscrmContractApplicationInfo->save();
                    }

                    break;
            }

        }

        return true;
    }


    public static function getmatchingRule($matching_rule,$contractId,$val)
    {
        //TODO 决定匹配规则 matching_rule = 1 名称&租期&类型  matching_rule = 2 名称&类型  matching_rule = 3 产品名称

        $where1 = [
            'contract_id' => $contractId,//合同id
            'application_id' => $val['application_id'],//产品id
            'rent_period' => $val['rent_period'],//租期
            'contract_type' => $val['contract_type'],//产品类型
        ];

        $where2 = [
            'contract_id' => $contractId,//合同id
            'application_id' => $val['application_id'],//产品id
            'contract_type' => $val['contract_type'],//产品类型
        ];


        $where3 = [
            'contract_id' => $contractId,//合同id
            'application_id' => $val['application_id'],//产品id
        ];

        if($matching_rule === 1){
            return $where1;
        }

        if($matching_rule === 2){
            return $where2;
        }

        if($matching_rule === 3){
            return $where3;
        }

        return [];
    }

    /**
     * 获取合同id所有标准签约产品（标准产品is_standard=1）
     * @param string $contractId 合同id
     * @return array
     */
    public static function getStandardContractApplicationByContractId($contractId)
    {
        return ContractApplicationEntity::find()->select("*")
            ->leftJoin("myscrm_application_info",
            "myscrm_application_info.application_id =myscrm_contract_application.application_id")
            ->leftJoin("myscrm_application_price",
                "myscrm_application_info.application_id =myscrm_application_price.application_id")
            ->where(['contract_id' => $contractId, 'myscrm_contract_application.is_standard' => 1])
            ->asArray()->all();
    }


    /**
     * 获取合同产品id获取标准签约产品（标准产品is_standard=1）
     * @param string $contractId 合同id
     * @return array
     */
    public static function getStandardContractApplicationByContractApplicationId($contractApplicationId)
    {
        return ContractApplicationEntity::find()->select("*")
            ->leftJoin("myscrm_application_info",
                "myscrm_application_info.application_id =myscrm_contract_application.application_id")
            ->leftJoin("myscrm_application_price",
                "myscrm_application_info.application_id =myscrm_application_price.application_id")
            ->where(['myscrm_contract_application.contract_application_id' => $contractApplicationId, 'myscrm_contract_application.is_standard' => 1])
            ->asArray()->one();
    }

    /**
     * 获取合同id所有签约产品
     * @param string $contractId 合同id
     * @return array
     */
    public static function getAllContractApplicationByContractId($contractId)
    {
        return ContractApplicationEntity::find()
            ->select("*")
            ->leftJoin("myscrm_application_info",
            "myscrm_application_info.application_id =myscrm_contract_application.application_id")
            ->where(['contract_id' => $contractId])
            ->asArray()
            ->all();
    }

    /**
     * 获取合同id所有业绩
     * @param string $contractId 合同id
     * @return array
     */
    public static function getAllAchievementByContractId($contractId)
    {
        return ContractApplicationEntity::find()
            ->select("*")
            ->from("myscrm_authorization_achievement")
            ->leftJoin("myscrm_application_info",
                "myscrm_application_info.application_id =myscrm_authorization_achievement.application_id")
            ->where(['contract_id' => $contractId])
            ->asArray()
            ->all();
    }

    /**
     * 根据合同id,判断是否存在产品
     * @param string $contractId 合同id
     * @return boolean
     */
    public static function isExistContractApplicationByContractId($contractId)
    {
        return ContractApplicationEntity::find()->where(['contract_id' => $contractId])->exists();
    }

    /**
     * 根据合同id,获取合同基本信息的产品
     * @param string $contractId 合同id
     * @return boolean
     */
    public static function getContractApplicationByContractId($contractId)
    {
        return ContractApplicationEntity::find()
            ->select("*")
            ->where(['contract_id' => $contractId])
            ->asArray()
            ->all();
    }


    /**
     * 根据合同contractid 获取合同基本信息产品
     * @param string $contractId 合同id
     * @return boolean
     */
    public static function getContractApplicationAppId($contractAppId)
    {
        return ContractApplicationEntity::find()->where(['contract_application_id' => $contractAppId])->one();
    }

    /**
     * 删除
     * @param $contractId
     * @return int
     */
    public static function deleteByContractId($contractId)
    {
        /** @var MyscrmContractSyncDeleteDataRepository $contractSyncDeleteDataRepository */
        $contractSyncDeleteDataRepository = \Yii::createObject(MyscrmContractSyncDeleteDataRepository::className());

        $deleteData = ContractApplicationEntity::findAll(["contract_id" => $contractId]);

        $deleteResult = ContractApplicationEntity::deleteAll(["contract_id" => $contractId]);

        if($deleteResult > 0){
            foreach ($deleteData as $data){
                $contractSyncDeleteDataRepository->add('myscrm_contract_application', 'contract_application_id', $data['contract_application_id']);
            }
        }

        return $deleteResult;
    }

    /**
     * 产品总额
     * @param $contractId
     * @return bool|string
     */
    public static function getAllAmountByContractId($contractId)
    {
        return ContractApplicationEntity::find()->select("sum(amount)")->where(['contract_id' => $contractId])->scalar();
    }

    /**
     * 更新字段
     * @param $id
     * @param $data
     */
    public static function updatedByPk($id, $data)
    {
        return ContractApplicationEntity::updateAll($data, "contract_application_id=:id", [":id" => $id]);
    }

    /**
     * 获取合同产品的ID
     *
     * @param $contractId
     * @param $applicationId
     * @param $num
     * @return bool|string
     */
    public static function getContractApplicationId($contractId, $applicationId, $num)
    {
        return ContractApplicationEntity::find()->select('contract_application_id')->where(['contract_id' => $contractId, 'application_id' => $applicationId, 'authorization_numeric' => $num])->scalar();
    }

    /**
     *
     * 根据合同ID、产品ID获取关联ID
     *
     * @param  $contractId     string
     * @param  $applicationId  string
     * @return bool|string
     */
    public static function getContractAppId($contractId, $applicationId)
    {
        $map = [
            'contract_id' => $contractId,
            'application_id' => $applicationId,
        ];

        return ContractApplicationEntity::find()->select('contract_application_id')->where($map)->scalar();
    }

    /**
     * 获取合同产品的基本信息
     *
     * @param $contractApplicationId
     * @return array|null|\yii\db\ActiveRecord
     */
    public static function getContractApplicationInfo($contractApplicationId)
    {
        return ContractApplicationEntity::find()->where(['contract_application_id' => $contractApplicationId])->asArray()->one();
    }

    /**
     * 获取achievementHandle所需要的合同产品信息
     *
     * @author    chenjy01
     * @version   1.0
     * @link      http://www.myunke.com/
     * @param     $contractId string 合同ID
     * @return    array
     */
    public static function getAchievementData($contractId)
    {
        $field = 'cAppObj.*,appObj.unique_name';

        $result =  ContractApplicationEntity::find()->where(['contract_id' => $contractId])
                                                    ->select($field)
                                                    ->from(ContractApplicationEntity::tableName() . ' AS cAppObj')
                                                    ->join('INNER JOIN', ApplicationInfoEntity::tableName() . ' AS appObj', 'cAppObj.application_id = appObj.application_id')
                                                    ->asArray()
                                                    ->all();

        return $result;
    }



}